package com.csg.web.controller;

import com.csg.web.amqp.Sender;
import com.csg.web.support.DeferredResultHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * 异步处理
 *
 * @author george
 */
@Slf4j
@RestController
@RequestMapping("/async")
public class AsyncController {

    /**
     * 消息发送者
     */
    @Autowired
    private Sender sender;

    /**
     * 同步方法
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/order1")
    public String order() throws InterruptedException {
        log.info("主线程 start");
        Thread.sleep(1000);
        log.info("主线程 end");
        return "success";
    }

    /**
     * 异步方法（Callable方式）
     *
     * @return
     */
    @GetMapping("/order2")
    public Callable<String> orderByCallable() {
        log.info("父线程 start");
        Callable<String> result = () -> {
            log.info("子线程 start");
            Thread.sleep(1000);
            log.info("子线程 end");
            return "success";
        };
        log.info("父线程 end");
        return result;
    }

    /**
     * 异步方法（DeferredResult方式）
     *
     * @return
     */
    @GetMapping("/order3")
    public DeferredResult<String> orderByDeferredResult() {
        log.info("主线程 start");
        String context = "hello" + System.currentTimeMillis();
        sender.send(context);
        DeferredResult<String> result = new DeferredResult<>();
        DeferredResultHolder.add(context, result);
        log.info("主线程 end");
        return result;
    }
}
